package com.acg.auth.service.impl;

import com.acg.auth.pojo.SysUser;
import com.acg.auth.service.SysMenuService;
import com.acg.auth.service.SysUserService;
import com.acg.security.custom.CustomUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description TODO
 * @Author 没有脑袋
 * @Date 2025/8/1 14:24
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private SysUserService userService;


    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 根据用户名查找用户
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 创建条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        // 进行查找
        SysUser sysUser = userService.getOne(queryWrapper);

        // 对user进行判断
        if (ObjectUtils.isEmpty(sysUser) ) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 比对密码
        //  异常不被 @ExceptionHandler 拦截
        //  @ExceptionHandler  只拦截控制器抛出的异常
        if (sysUser.getStatus().equals(0)) {

            // 安全框架中的异常filter 进行拦截
            throw new UsernameNotFoundException("该用户已经被禁用");
        }
//        // 用户授权
//
//        // 按钮权限
        List<String> userPermsList = sysMenuService.findUserPermsList(sysUser.getId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String perm : userPermsList) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }
        return new CustomUser(sysUser, authorities);
//        return new CustomUser(sysUser, null);
    }
}
